<script setup lang="ts">
import { type UploadUserFile, type UploadProps, ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'

// 抽屉显示隐藏
const visible = ref(false)
function open() {
  visible.value = true
}

// 文件上传列表
const fileList = ref<UploadUserFile[]>([])
const customUploadRequest: UploadProps['httpRequest'] = ({
  file,
  headers,
  data,
  withCredentials
}) => {
  console.log('上传：', file, headers, data, withCredentials)
  return Promise.resolve({
    data: {
      url: 'https://www.baidu.com'
    }
  })
}
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file, uploadFiles)
}
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  console.log(files, uploadFiles)
  ElMessage.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件`)
}
const beforeRemove: UploadProps['beforeRemove'] = (file) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`).then(
    () => true,
    () => false
  )
}

// 暴露方法
defineExpose({
  open
})
</script>

<template>
  <el-drawer v-model="visible" title="上传素材" size="40%">
    <el-upload
      v-model="fileList"
      :http-request="customUploadRequest"
      drag
      multiple
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :limit="3"
      :on-exceed="handleExceed"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text"> 拖动文件到这里或者 <em>点击上传</em> </div>
      <template #tip>
        <div class="el-upload__tip"> 文件大小不可超过 100 M </div>
      </template>
    </el-upload>
  </el-drawer>
</template>

<style scoped></style>
